import React, {
  useState,
  useEffect,
  useRef,
  useImperativeHandle,
  forwardRef,
} from "react";
import { Upload, Modal } from "antd";
import { PlusOutlined } from "@ant-design/icons";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

const PicturesWall = forwardRef(({ imgs }, ref) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    if (imgs && imgs.length > 0) {
      const newFileList = imgs.map((imgName, i) => ({
        uid: -i,
        name: imgName,
        status: "done",
        url: "http://localhost:5000/upload/" + imgName,
      }));
      setFileList(newFileList);
    }
  }, [imgs]);

  useImperativeHandle(ref, () => ({
    getImgs: () => fileList.map((file) => file.name),
  }));

  const handleCancel = () => setPreviewOpen(false);

  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
  };

  const handleChange = ({ file, fileList: newFileList }) => {
    if (file.status === "done") {
      const { name, url } = file.response.data;
      const index = newFileList.findIndex((f) => f.uid === file.uid);
      if (index !== -1) {
        newFileList[index].name = name;
        newFileList[index].url = url;
      }
    }
    setFileList(newFileList);
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <div className="clearfix">
      <Upload
        action="/manage/img/upload"
        name="image"
        listType="picture-card"
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
      >
        {fileList.length >= 3 ? null : uploadButton}
      </Upload>
      <Modal visible={previewOpen} footer={null} onCancel={handleCancel}>
        <img alt="example" style={{ width: "100%" }} src={previewImage} />
      </Modal>
    </div>
  );
});

export default PicturesWall;
